
#include "toolkit.h"
#include <windows.h>
#include <cstring>
#include <unknwn.h>   //   Declare   IUnknown.
#define _WIN32_IE 0x0500
#include <shlobj.h>

#include <iostream>
#include <fstream>
#include <iterator>
#include <windows.h>
#include <wx/choicdlg.h>



//Class initialize
//namespace po = boost::program_options;

/*
int DoubleBall::nrow=0;
int DoubleBall::ncol=0;
sqlite3 *DoubleBall::db=NULL;
char** DoubleBall::records=NULL;
char *DoubleBall::zErrMsg=0;
*/
char  DoubleBall::DB_LOCATION_HOME[1024]="C:\\DoubleBallBonus\\org\\security\\database\\doubleball.db3";
/*
char  DoubleBall::DB_LOCATION_OFFICE[1024]="D:\\test_Projects\\Gate\\WebContent\\WEB-INF\\classes\\org\\security\\database\\doubleball.db3";
*/
char  DoubleBall::QUERY_DB[4096]="SELECT rowid,* FROM _DBHISTORY order by term asc";

     char  DoubleBall::_LastTermOrder[20]="";//最后一期数据
     char  DoubleBall::_LastTermDate[20]="";//最后一期日期
     char  DoubleBall::_FirstTermOrder[20]="";//第一期数据
     char  DoubleBall::_FirstTermDate[20]="";//第一期数据
     char * DoubleBall::_DEFAULTDBNAME="doubleball.db3";//默认的数据库的名字
using namespace std;
DoubleBall::DoubleBall(const char * homedir): rc(0),db_open(0),records(0),db(0),zErrMsg(0)
{
 strcpy(DoubleBall::DB_LOCATION_HOME,homedir);
}
DoubleBall::DoubleBall(): rc(0),db_open(0),records(0),db(0),zErrMsg(0)
{
db=NULL;
records=NULL;
zErrMsg=NULL;
checkDatabase();
}
/*
检查数据库是否存在
*/
bool DoubleBall::checkDatabase()
{
  //  MessageBoxA(NULL,DB_LOCATION_HOME,NULL,NULL);
   char buffer [1024];
      rc = sqlite3_open(DB_LOCATION_HOME, &db);


      if(rc)
      {
        sprintf(buffer, "Can't open database: %s %s\n",DoubleBall::DB_LOCATION_HOME, sqlite3_errmsg(db));
        MessageBoxA(NULL,(buffer),NULL,NULL);
        sqlite3_close(db);
      }
//here is 自己定义的函数
     rc = sqlite3_create_function(db, "msign", 1, SQLITE_UTF8, NULL,&msignFunc, NULL, NULL);
  if(rc !=0 )MessageBoxW(NULL,wxT("自定义函数创建不成功！"),NULL,NULL);

      db_open=1;
}
int DoubleBall::query(char * sql)
{
zErrMsg=NULL;
        rc = sqlite3_get_table
        (
  			db,              /* An open database */
  			sql,       /* SQL to be executed */
  			&records,       /* Result written to a char *[]  that this points to */
  			&nrow,             /* Number of result rows written here */
  			&ncol,          /* Number of result columns written here */
  			&zErrMsg          /* Error msg written here */
  			);
if(zErrMsg!=NULL)
{

  MessageBoxA(NULL,zErrMsg,NULL,NULL);
  zErrMsg=NULL;
}

        return rc;
}
int DoubleBall::executeCRUD(const char * sql)
{
int result=true;
char *pErrMsg = 0;

//assert(zErrMsg!=NULL);
  int code=sqlite3_exec(db,sql,NULL,NULL,&pErrMsg);

 if(code!=SQLITE_OK)
    {
    MessageBoxA(NULL,pErrMsg,NULL,NULL);
    result=false;
    }
   return result;
}


DoubleBall::~DoubleBall()
{
      if(records!=NULL)
      {
	     sqlite3_free_table(records);
	     records=NULL;
      }

	if(db!=NULL)
		{

        sqlite3_close(db);

        db=NULL;
        }
//MessageBox(NULL,"close db connect ok,get out",NULL,NULL);
}

void DoubleBall::initialize()//复位全局数据指示
{
 char *SQL="select * from _DBHISTORY order by term asc";
 query(SQL);
//第一行是列的标题栏
//Last term
//MessageBoxA(NULL,"initialize.... start",NULL,NULL);

if(records!=NULL && nrow>0)
{
strcpy(_LastTermOrder,records[(nrow)*ncol]);
strcpy(_LastTermDate,records[(nrow)*ncol +1]);
strcpy(_FirstTermOrder,records[1*ncol]);
strcpy(_FirstTermDate,records[1*ncol +1]);
}else
{
     MessageBoxW(NULL,wxT("历史记录为空,需要更新"),NULL,NULL);
}
//MessageBoxA(NULL,"initialize.... end",NULL,NULL);

}

/*打印彩色文字*/
void printColorText(char * str,unsigned short color)
{
char* cstr="";
switch(color)
 {
 case FOREGROUND_RED:cstr="31m";
 	break;
 case FOREGROUND_BLUE:cstr="7;34m";
 	}
if(MINGW_FLAG==0)//cygwin Linux simulator mode
	{
 printf("\033[1;%s%s\033[0m\t",cstr,str);
	}else
	{
HANDLE Console_Handle = GetStdHandle( STD_OUTPUT_HANDLE );
const int saved_colors = GetConsoleTextAttribute(Console_Handle);
switch(color)
{
 case FOREGROUND_RED:
 	SetConsoleTextAttribute(Console_Handle, color|FOREGROUND_INTENSITY);
 	break;
 case FOREGROUND_BLUE:
 	SetConsoleTextAttribute(Console_Handle, color|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY);
}
printf("%s\t",str);
SetConsoleTextAttribute(Console_Handle, saved_colors);
  }
}
unsigned short GetConsoleTextAttribute (void * hCon)
{
  CONSOLE_SCREEN_BUFFER_INFO con_info;
  GetConsoleScreenBufferInfo(hCon, &con_info);
  return con_info.wAttributes;
}
int  getWeek(unsigned year,unsigned month,unsigned day)
{
struct tm date,*ptm;
 time_t t;

 memset(&date, 0x0, sizeof(struct tm));

 //2009-4-21
 date.tm_year = year -1900;
 date.tm_mon  = month  - 1;
 date.tm_mday = day;

 t = mktime(&date);
 ptm = localtime(&t);
 return  ptm->tm_wday;
}

//得到屏幕宽度
int getScreenWidth()
 {
return GetSystemMetrics(SM_CXSCREEN);
 }
 //得到屏幕高度
int getScreenHeight()
 {
return GetSystemMetrics(SM_CYSCREEN );
 }

//检查sqlite3.dll是否存在
bool checkSQLite3()
{
   //find dll library
  HINSTANCE   hComponent   =   ::LoadLibraryA("sqlite3.dll");
  if   (hComponent   ==   NULL)
  {
  printf("CallCreateInstance:\tError:Cannot   load   component.");
  return   false;
  }
  return true;
}

/*
// Read INI File Code in a C gauge. Display pilot's name as a string.
//get current user home dir
  char   szPath[MAX_PATH];
  SHGetSpecialFolderPath(0,szPath,CSIDL_PERSONAL   ,0);
getEnv("USERPROFILE");
*/
string getUserHome()
{
 int opt;
  char   szPath[MAX_PATH];
  SHGetSpecialFolderPathA(NULL,szPath,CSIDL_PERSONAL  ,0);
 return string(szPath);
}
void createDatabase()
{
static int dbs =9;
char* createMainDB[9]=
{
"CREATE TABLE IF NOT EXISTS  _DBHISTORY (term varchar(30) PRIMARY KEY ,date date,red1 int,red2 int,red3 int,red4 int,red5 int,red6 int,blue int)",
"CREATE TABLE IF NOT EXISTS  _NOTES (term vharchar(30) NOT NULL ,no INTEGER NOT NULL ,notes TEXT NOT NULL ,createdate DATETIME NOT NULL  DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (term,no) )",
"CREATE TABLE IF NOT EXISTS  _COLLECTIONNUMBER (redball INTEGER PRIMARY KEY  NOT NULL , num1 INTEGER, num2 INTEGER, num3 INTEGER, num4 INTEGER, num5 INTEGER, num6 INTEGER, num7 INTEGER, num8 INTEGER, num9 INTEGER, num10 INTEGER, num11 INTEGER, num12 INTEGER, num13 INTEGER, num14 INTEGER, num15 INTEGER, num16 INTEGER, num17 INTEGER, num18 INTEGER, num19 INTEGER, num20 INTEGER, num21 INTEGER, num22 INTEGER, num23 INTEGER, num24 INTEGER, num25 INTEGER, num26 INTEGER, num27 INTEGER, num28 INTEGER, num29 INTEGER, num30 INTEGER, num31 INTEGER, num32 INTEGER, num33 INTEGER )",
"CREATE TABLE IF NOT EXISTS  _ENTROPYSUM(term varchar(30),date date,SumofSquares INTEGER,/*离差平方和 */PowerSum INTEGER,/*平方和 */PartialSum INTEGER,/*数字和*/Range INTEGER,/*极差*/PRIMARY KEY (term))",
"CREATE TABLE IF NOT EXISTS  _FIVEENTROPY(term varchar(30),date date, num1 INTEGER, num2 INTEGER, num3 INTEGER, num4 INTEGER, num5 INTEGER, num6 INTEGER, num7 INTEGER, num8 INTEGER, num9 INTEGER,num10 INTEGER,num11 INTEGER,num12 INTEGER,num13 INTEGER,num14 INTEGER,num15 INTEGER,num16 INTEGER,num17 INTEGER,num18 INTEGER,num19 INTEGER,num20 INTEGER,num21 INTEGER,num22 INTEGER,num23 INTEGER,num24 INTEGER,num25 INTEGER,num26 INTEGER,num27 INTEGER,num28 INTEGER,num29 INTEGER,num30 INTEGER,num31 INTEGER,num32 INTEGER,num33 INTEGER,PRIMARY KEY (term))",
"CREATE TABLE IF NOT EXISTS  _FORECAST(id INTEGER PRIMARY KEY AUTOINCREMENT,term varchar(30),date date, num1 INTEGER, num2 INTEGER, num3 INTEGER, num4 INTEGER, num5 INTEGER, num6 INTEGER, num7 INTEGER, num8 INTEGER, num9 INTEGER,num10 INTEGER,num11 INTEGER,num12 INTEGER,num13 INTEGER,num14 INTEGER,num15 INTEGER,num16 INTEGER,num17 INTEGER,num18 INTEGER,num19 INTEGER,num20 INTEGER,num21 INTEGER,num22 INTEGER,num23 INTEGER,num24 INTEGER,num25 INTEGER,num26 INTEGER,num27 INTEGER,num28 INTEGER,num29 INTEGER,num30 INTEGER,num31 INTEGER,num32 INTEGER,num33 INTEGER,blue  INTEGER,remarks TEXT,createdate DATETIME)",
"CREATE TABLE IF NOT EXISTS  _FRACTALSUM (term VARCHAR(30) NOT NULL , date date NOT NULL , num0 INTEGER NOT NULL  DEFAULT 0, num1 INTEGER NOT NULL  DEFAULT 0, num2 INTEGER NOT NULL  DEFAULT 0, num3 INTEGER NOT NULL  DEFAULT 0, num4 INTEGER NOT NULL  DEFAULT 0, num5 INTEGER NOT NULL  DEFAULT 0, num6 INTEGER NOT NULL  DEFAULT 0, num7 INTEGER NOT NULL  DEFAULT 0, num8 INTEGER NOT NULL  DEFAULT 0, num9 INTEGER NOT NULL  DEFAULT 0, PRIMARY KEY (term, num0, num1, num2, num3, num4, num5, num6, num7, num8, num9))",
"CREATE TABLE IF NOT EXISTS  _SIMPLEENTROPY(term varchar(30),date date, num1 INTEGER, num2 INTEGER, num3 INTEGER, num4 INTEGER, num5 INTEGER, num6 INTEGER, num7 INTEGER, num8 INTEGER, num9 INTEGER,num10 INTEGER,num11 INTEGER,num12 INTEGER,num13 INTEGER,num14 INTEGER,num15 INTEGER,num16 INTEGER,num17 INTEGER,num18 INTEGER,num19 INTEGER,num20 INTEGER,num21 INTEGER,num22 INTEGER,num23 INTEGER,num24 INTEGER,num25 INTEGER,num26 INTEGER,num27 INTEGER,num28 INTEGER,num29 INTEGER,num30 INTEGER,num31 INTEGER,num32 INTEGER,num33 INTEGER,PRIMARY KEY (term))",
"CREATE TABLE IF NOT EXISTS  _LISPLET(id INTEGER PRIMARY KEY AUTOINCREMENT,name varchar(100),codes text,flag char(1),createdate DATETIME NOT NULL  DEFAULT CURRENT_TIMESTAMP,modifydate DATETIME NOT NULL  DEFAULT CURRENT_TIMESTAMP )"
};
DoubleBall * db=new DoubleBall((wxGetHomeDir()+_("\\")+wxString(DoubleBall::_DEFAULTDBNAME,wxConvUTF8)).mb_str(wxConvUTF8));
if(db->checkDatabase()){delete db;return;}//check daabase
for(int i=0;i<dbs;i++)
  {
   db->executeCRUD(createMainDB[i]);
  }
delete db;
}

void msignFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
{
  assert( argc==1 );
  switch( sqlite3_value_type(argv[0]) ){
    case SQLITE_INTEGER: {
      long long int iVal = sqlite3_value_int64(argv[0]);
      iVal = ( iVal > 0) ? 1: ( iVal < 0 ) ? -1: 0;
      sqlite3_result_int64(context, iVal);
      break;
    }
    case SQLITE_NULL: {
      sqlite3_result_null(context);
      break;
    }
    default: {
      double rVal = sqlite3_value_double(argv[0]);
      rVal = ( rVal > 0) ? 1: ( rVal < 0 ) ? -1: 0;
      sqlite3_result_double(context, rVal);
      break;
    }
  }
}

